/*
 * Tencent is pleased to support the open source community by making ovCompose available.
 * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tencent.compose.sample.test

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlin.random.Random

/**
 * 测试数据生成器
 */
object TestDataGenerator {
    
    private val names = listOf(
        "张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十",
        "郑十一", "王十二", "冯十三", "陈十四", "褚十五", "卫十六",
        "蒋十七", "沈十八", "韩十九", "杨二十", "朱二十一", "秦二十二"
    )
    
    private val emails = listOf(
        "zhang@example.com", "li@example.com", "wang@example.com",
        "zhao@example.com", "qian@example.com", "sun@example.com",
        "zhou@example.com", "wu@example.com", "zheng@example.com",
        "feng@example.com", "chen@example.com", "chu@example.com"
    )
    
    private val productNames = listOf(
        "智能手机", "笔记本电脑", "平板电脑", "无线耳机", "智能手表",
        "蓝牙音箱", "游戏手柄", "机械键盘", "电竞鼠标", "显示器",
        "移动硬盘", "U盘", "充电宝", "数据线", "保护壳"
    )
    
    private val productDescriptions = listOf(
        "高性能产品，质量可靠", "时尚设计，功能强大", "性价比极高",
        "专业级产品，适合专业人士", "创新技术，领先行业",
        "用户好评如潮", "品质保证，值得信赖", "最新技术，前沿体验"
    )
    
    private val streetNames = listOf(
        "中山路", "解放路", "人民路", "建设路", "和平路",
        "光明路", "胜利路", "友谊路", "团结路", "和谐路"
    )
    
    private val cities = listOf(
        "北京", "上海", "广州", "深圳", "杭州", "南京", "武汉", "成都",
        "西安", "重庆", "天津", "苏州", "长沙", "青岛", "大连", "厦门"
    )
    
    /**
     * 生成测试用户
     */
    fun generateTestUser(id: Long = Random.nextLong(1, 10000)): TestUser {
        val name = names.random()
        val email = emails.random()
        val age = Random.nextInt(18, 65)
        
        return TestUser(
            id = id,
            name = name,
            email = email,
            age = age,
            avatar = "https://example.com/avatar/${id}.jpg",
            isActive = Random.nextBoolean(),
            createdAt = System.currentTimeMillis() - Random.nextLong(0, 365 * 24 * 60 * 60 * 1000),
            preferences = generateUserPreferences()
        )
    }
    
    /**
     * 生成用户偏好设置
     */
    private fun generateUserPreferences(): UserPreferences {
        return UserPreferences(
            theme = listOf("light", "dark", "auto").random(),
            language = listOf("zh", "en", "ja", "ko").random(),
            notifications = Random.nextBoolean(),
            autoSave = Random.nextBoolean(),
            fontSize = Random.nextInt(12, 20)
        )
    }
    
    /**
     * 生成测试商品
     */
    fun generateTestProduct(id: String = Random.nextLong(1, 10000).toString()): TestProduct {
        val name = productNames.random()
        val description = productDescriptions.random()
        val price = Random.nextDouble(10.0, 10000.0)
        val category = ProductCategory.values().random()
        
        return TestProduct(
            id = id,
            name = name,
            description = description,
            price = price,
            currency = "CNY",
            category = category,
            images = generateImageUrls(),
            rating = Random.nextDouble(1.0, 5.0),
            reviewCount = Random.nextInt(0, 1000),
            inStock = Random.nextBoolean(),
            tags = generateTags(category),
            specifications = generateSpecifications(category)
        )
    }
    
    /**
     * 生成图片URL列表
     */
    private fun generateImageUrls(): List<String> {
        val count = Random.nextInt(1, 5)
        return (1..count).map { "https://example.com/images/product_${Random.nextLong(1, 1000)}.jpg" }
    }
    
    /**
     * 生成标签
     */
    private fun generateTags(category: ProductCategory): List<String> {
        val baseTags = when (category) {
            ProductCategory.ELECTRONICS -> listOf("科技", "创新", "智能")
            ProductCategory.CLOTHING -> listOf("时尚", "舒适", "品质")
            ProductCategory.BOOKS -> listOf("知识", "学习", "教育")
            ProductCategory.HOME -> listOf("实用", "美观", "耐用")
            ProductCategory.SPORTS -> listOf("运动", "健康", "活力")
            ProductCategory.BEAUTY -> listOf("美容", "护肤", "时尚")
            ProductCategory.FOOD -> listOf("美味", "新鲜", "健康")
            ProductCategory.OTHER -> listOf("特色", "独特", "精选")
        }
        
        return baseTags.shuffled().take(Random.nextInt(1, 4))
    }
    
    /**
     * 生成规格信息
     */
    private fun generateSpecifications(category: ProductCategory): Map<String, String> {
        return when (category) {
            ProductCategory.ELECTRONICS -> mapOf(
                "品牌" to "测试品牌",
                "型号" to "T${Random.nextInt(1000, 9999)}",
                "颜色" to listOf("黑色", "白色", "银色", "金色").random(),
                "重量" to "${Random.nextInt(100, 2000)}g"
            )
            ProductCategory.CLOTHING -> mapOf(
                "材质" to listOf("棉", "涤纶", "羊毛", "丝绸").random(),
                "尺码" to listOf("S", "M", "L", "XL", "XXL").random(),
                "颜色" to listOf("黑色", "白色", "红色", "蓝色", "绿色").random()
            )
            else -> mapOf(
                "规格" to "标准规格",
                "产地" to "中国",
                "保质期" to "${Random.nextInt(1, 24)}个月"
            )
        }
    }
    
    /**
     * 生成测试订单
     */
    fun generateTestOrder(id: String = Random.nextLong(1, 10000).toString()): TestOrder {
        val userId = Random.nextLong(1, 1000)
        val items = generateOrderItems()
        val totalAmount = items.sumOf { it.totalPrice }
        
        return TestOrder(
            id = id,
            userId = userId,
            items = items,
            totalAmount = totalAmount,
            currency = "CNY",
            status = OrderStatus.values().random(),
            shippingAddress = generateAddress(),
            billingAddress = if (Random.nextBoolean()) generateAddress() else null,
            paymentMethod = PaymentMethod.values().random(),
            createdAt = System.currentTimeMillis() - Random.nextLong(0, 30 * 24 * 60 * 60 * 1000),
            updatedAt = System.currentTimeMillis(),
            notes = if (Random.nextBoolean()) "请小心轻放" else null
        )
    }
    
    /**
     * 生成订单项
     */
    private fun generateOrderItems(): List<OrderItem> {
        val count = Random.nextInt(1, 5)
        return (1..count).map {
            val productId = Random.nextLong(1, 1000).toString()
            val productName = productNames.random()
            val quantity = Random.nextInt(1, 10)
            val unitPrice = Random.nextDouble(10.0, 1000.0)
            
            OrderItem(
                productId = productId,
                productName = productName,
                quantity = quantity,
                unitPrice = unitPrice,
                totalPrice = unitPrice * quantity
            )
        }
    }
    
    /**
     * 生成地址
     */
    private fun generateAddress(): Address {
        return Address(
            id = Random.nextLong(1, 1000).toString(),
            recipientName = names.random(),
            phoneNumber = "1${Random.nextInt(300000000, 999999999)}",
            street = "${streetNames.random()}${Random.nextInt(1, 999)}号",
            city = cities.random(),
            state = "省",
            postalCode = "${Random.nextInt(100000, 999999)}",
            country = "中国",
            isDefault = Random.nextBoolean()
        )
    }
    
    /**
     * 生成测试消息
     */
    fun generateTestMessage(id: String = Random.nextLong(1, 10000).toString()): TestMessage {
        val senderId = Random.nextLong(1, 1000)
        val receiverId = Random.nextLong(1, 1000)
        
        return TestMessage(
            id = id,
            senderId = senderId,
            receiverId = receiverId,
            content = generateMessageContent(),
            type = MessageType.values().random(),
            timestamp = System.currentTimeMillis() - Random.nextLong(0, 7 * 24 * 60 * 60 * 1000),
            isRead = Random.nextBoolean(),
            attachments = if (Random.nextBoolean()) generateAttachments() else emptyList(),
            replyTo = if (Random.nextBoolean()) Random.nextLong(1, 1000).toString() else null
        )
    }
    
    /**
     * 生成消息内容
     */
    private fun generateMessageContent(): String {
        val contents = listOf(
            "你好，最近怎么样？",
            "这个产品看起来很不错！",
            "谢谢你的帮助",
            "我们什么时候见面？",
            "工作进展如何？",
            "周末有什么计划吗？",
            "这个价格可以接受",
            "质量怎么样？",
            "什么时候发货？",
            "收到货了，很满意！"
        )
        return contents.random()
    }
    
    /**
     * 生成附件
     */
    private fun generateAttachments(): List<Attachment> {
        val count = Random.nextInt(1, 3)
        return (1..count).map {
            Attachment(
                id = Random.nextLong(1, 1000).toString(),
                name = "attachment_${it}.${listOf("jpg", "pdf", "doc", "mp4").random()}",
                url = "https://example.com/files/attachment_${it}",
                size = Random.nextLong(1024, 10 * 1024 * 1024),
                mimeType = "application/octet-stream",
                thumbnailUrl = "https://example.com/thumbnails/attachment_${it}_thumb.jpg"
            )
        }
    }
    
    /**
     * 生成测试事件
     */
    fun generateTestEvent(id: String = Random.nextLong(1, 10000).toString()): TestEvent {
        val startTime = System.currentTimeMillis() + Random.nextLong(0, 30 * 24 * 60 * 60 * 1000)
        val endTime = startTime + Random.nextLong(1 * 60 * 60 * 1000, 8 * 60 * 60 * 1000)
        
        return TestEvent(
            id = id,
            title = generateEventTitle(),
            description = generateEventDescription(),
            startTime = startTime,
            endTime = endTime,
            location = if (Random.nextBoolean()) generateEventLocation() else null,
            organizer = names.random(),
            attendees = generateAttendees(),
            maxAttendees = Random.nextInt(10, 500),
            category = EventCategory.values().random(),
            isPublic = Random.nextBoolean(),
            tags = generateEventTags(),
            imageUrl = if (Random.nextBoolean()) "https://example.com/events/event_${id}.jpg" else null
        )
    }
    
    /**
     * 生成事件标题
     */
    private fun generateEventTitle(): String {
        val titles = listOf(
            "技术分享会", "产品发布会", "用户交流会", "培训讲座",
            "年会庆典", "团建活动", "学术研讨会", "创业路演",
            "艺术展览", "音乐会", "体育比赛", "慈善活动"
        )
        return titles.random()
    }
    
    /**
     * 生成事件描述
     */
    private fun generateEventDescription(): String {
        val descriptions = listOf(
            "这是一个精彩的活动，欢迎大家参加",
            "专业的内容分享，不容错过",
            "互动性强，参与度高",
            "适合各年龄段的朋友",
            "免费参加，名额有限",
            "有丰富的奖品等你来拿"
        )
        return descriptions.random()
    }
    
    /**
     * 生成事件地点
     */
    private fun generateEventLocation(): String {
        val locations = listOf(
            "北京国际会议中心", "上海展览中心", "深圳会展中心",
            "广州白云国际会议中心", "杭州国际博览中心", "南京国际展览中心",
            "武汉国际博览中心", "成都世纪城新国际会展中心"
        )
        return locations.random()
    }
    
    /**
     * 生成参与者列表
     */
    private fun generateAttendees(): List<Long> {
        val count = Random.nextInt(0, 50)
        return (1..count).map { Random.nextLong(1, 1000) }
    }
    
    /**
     * 生成事件标签
     */
    private fun generateEventTags(): List<String> {
        val tags = listOf("热门", "免费", "限时", "专业", "互动", "创新", "实用", "有趣")
        return tags.shuffled().take(Random.nextInt(1, 4))
    }
    
    /**
     * 生成测试配置
     */
    fun generateTestConfig(): TestConfig {
        return TestConfig(
            appVersion = "1.${Random.nextInt(0, 9)}.${Random.nextInt(0, 99)}",
            apiBaseUrl = "https://api.example.com/v${Random.nextInt(1, 3)}",
            enableAnalytics = Random.nextBoolean(),
            enableCrashReporting = Random.nextBoolean(),
            enablePushNotifications = Random.nextBoolean(),
            cacheExpirationTime = Random.nextLong(1800000, 7200000),
            maxRetryAttempts = Random.nextInt(1, 5),
            timeoutDuration = Random.nextLong(10000, 60000),
            features = mapOf(
                "darkMode" to Random.nextBoolean(),
                "offlineMode" to Random.nextBoolean(),
                "biometricAuth" to Random.nextBoolean(),
                "voiceSearch" to Random.nextBoolean()
            ),
            limits = mapOf(
                "maxFileSize" to Random.nextInt(10, 100),
                "maxUploads" to Random.nextInt(5, 20),
                "maxConnections" to Random.nextInt(5, 50)
            )
        )
    }
    
    /**
     * 生成测试统计数据
     */
    fun generateTestStatistics(): TestStatistics {
        return TestStatistics(
            totalUsers = Random.nextLong(1000, 100000),
            activeUsers = Random.nextLong(100, 10000),
            totalOrders = Random.nextLong(5000, 500000),
            totalRevenue = Random.nextDouble(100000.0, 10000000.0),
            averageOrderValue = Random.nextDouble(50.0, 500.0),
            conversionRate = Random.nextDouble(0.01, 0.15),
            retentionRate = Random.nextDouble(0.3, 0.9),
            topProducts = generateTopProducts(),
            monthlyGrowth = generateMonthlyGrowth(),
            lastUpdated = System.currentTimeMillis()
        )
    }
    
    /**
     * 生成热门产品
     */
    private fun generateTopProducts(): List<ProductStats> {
        val count = Random.nextInt(5, 15)
        return (1..count).map {
            ProductStats(
                productId = Random.nextLong(1, 1000).toString(),
                productName = productNames.random(),
                salesCount = Random.nextInt(100, 10000),
                revenue = Random.nextDouble(1000.0, 100000.0),
                rating = Random.nextDouble(3.0, 5.0)
            )
        }
    }
    
    /**
     * 生成月度增长数据
     */
    private fun generateMonthlyGrowth(): List<MonthlyGrowth> {
        val months = listOf("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月")
        val currentYear = 2024
        
        return months.map { month ->
            MonthlyGrowth(
                month = month,
                year = currentYear,
                userGrowth = Random.nextDouble(-0.1, 0.3),
                revenueGrowth = Random.nextDouble(-0.05, 0.25),
                orderGrowth = Random.nextDouble(-0.08, 0.2)
            )
        }
    }
    
    /**
     * 生成用户数据流
     */
    fun generateUserFlow(): Flow<TestUser> = flow {
        while (true) {
            emit(generateTestUser())
            delay(Random.nextLong(1000, 5000))
        }
    }
    
    /**
     * 生成产品数据流
     */
    fun generateProductFlow(): Flow<TestProduct> = flow {
        while (true) {
            emit(generateTestProduct())
            delay(Random.nextLong(2000, 8000))
        }
    }
    
    /**
     * 生成订单数据流
     */
    fun generateOrderFlow(): Flow<TestOrder> = flow {
        while (true) {
            emit(generateTestOrder())
            delay(Random.nextLong(3000, 10000))
        }
    }
}
